"""
定时任务管理
"""
from flask import Blueprint, render_template, request, jsonify, current_app
from apps.common.utils.rights import authorize
from apps.modules.admin.models.sys.sys_task import Task
from apps.extensions import db, scheduler
from apps.modules.admin.tasks import get_task_functions, get_task_function
from apscheduler.triggers.date import DateTrigger
from apscheduler.triggers.interval import IntervalTrigger
from apscheduler.triggers.cron import CronTrigger
import json
import datetime

task_bp = Blueprint('task', __name__, url_prefix='/task')

@task_bp.route('/')
@authorize('admin:task:main', log=True)
def main():
    """定时任务主页面"""
    return render_template('system/task/main.html')


@task_bp.route('/data')
@authorize('admin:task:main')
def get_task_data():
    """获取任务列表数据"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('limit', 10, type=int)
        
        # 查询任务
        query = Task.query
        total = query.count()
        
        # 分页
        tasks = query.order_by(Task.created_at.desc()).offset((page - 1) * per_page).limit(per_page).all()
        
        # 转换为字典
        task_list = []
        for task in tasks:
            task_dict = task.to_dict()
            # 获取任务状态
            job_status = scheduler.get_job_status(task.id)
            if job_status:
                task_dict['next_run_time'] = job_status['next_run_time']
                task_dict['enabled'] = job_status['enabled']
            task_list.append(task_dict)
        
        return jsonify({
            'code': 0,
            'msg': '获取成功',
            'count': total,
            'data': task_list
        })
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'msg': f'获取任务列表失败: {str(e)}',
            'count': 0,
            'data': []
        })

@task_bp.route('/add')
@authorize('admin:task:add')
def add():
    """新增任务页面"""
    task_functions = get_task_functions()
    return render_template('system/task/add.html', task_list=task_functions)

@task_bp.route('/edit/<task_id>')
@authorize('admin:task:edit')
def edit(task_id):
    """编辑任务页面"""
    try:
        task = Task.query.get(task_id)
        if not task:
            return jsonify({'success': False, 'msg': '任务不存在'})
        
        # 处理trigger_args，确保它是字符串格式
        if task.trigger_args and isinstance(task.trigger_args, str):
            try:
                # 验证JSON格式
                json.loads(task.trigger_args)
            except json.JSONDecodeError:
                task.trigger_args = '{}'
        elif not task.trigger_args:
            task.trigger_args = '{}'
        
        task_functions = get_task_functions()
        return render_template('system/task/edit.html', task=task, task_list=task_functions)
        
    except Exception as e:
        return jsonify({'success': False, 'msg': f'加载任务失败: {str(e)}'})

@task_bp.route('/save', methods=['POST'])
@authorize('admin:task:add')
def save():
    """保存任务"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('id') or not data.get('name') or not data.get('functions'):
            return jsonify({'success': False, 'msg': '请填写必填字段'})
        
        # 检查任务ID是否已存在
        existing_task = Task.query.get(data['id'])
        if existing_task:
            return jsonify({'success': False, 'msg': '任务ID已存在'})
        
        # 创建任务对象
        task = Task(
            id=data['id'],
            name=data['name'],
            func=data['functions'],
            trigger=data.get('type', 'date'),
            enabled=True
        )
        
        # 设置触发器参数
        trigger_args = {}
        if data.get('type') == 'date':
            if data.get('datetime'):
                task.start_date = datetime.datetime.strptime(data['datetime'], '%Y-%m-%d %H:%M:%S')
        elif data.get('type') == 'interval':
            if data.get('time'):
                try:
                    # 尝试解析JSON格式的时间参数
                    trigger_args = json.loads(data['time'])
                except json.JSONDecodeError:
                    # 如果不是JSON，尝试解析时间间隔格式
                    time_parts = data['time'].split(':')
                    if len(time_parts) == 3:
                        hours = int(time_parts[0])
                        minutes = int(time_parts[1])
                        seconds = int(time_parts[2])
                        trigger_args = {
                            'hours': hours,
                            'minutes': minutes,
                            'seconds': seconds
                        }
        elif data.get('type') == 'cron':
            if data.get('time'):
                try:
                    # 尝试解析JSON格式的时间参数
                    trigger_args = json.loads(data['time'])
                except json.JSONDecodeError:
                    # 如果不是JSON，尝试解析cron格式
                    time_parts = data['time'].split(':')
                    if len(time_parts) == 2:
                        trigger_args = {
                            'hour': int(time_parts[0]),
                            'minute': int(time_parts[1])
                        }
        
        task.trigger_args = json.dumps(trigger_args)
        
        # 保存到数据库
        db.session.add(task)
        db.session.commit()
        
        # 添加到调度器
        from apps.extensions.scheduler import add_job_from_task
        job = add_job_from_task(task)
        
        if job:
            return jsonify({'success': True, 'msg': '任务创建成功'})
        else:
            return jsonify({'success': False, 'msg': '任务创建成功，但添加到调度器失败'})
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'msg': f'创建任务失败: {str(e)}'})

@task_bp.route('/update/<task_id>', methods=['POST'])
@authorize('admin:task:edit')
def update(task_id):
    """更新任务"""
    try:
        task = Task.query.get(task_id)
        if not task:
            return jsonify({'success': False, 'msg': '任务不存在'})
        
        data = request.get_json()
        
        # 更新任务信息
        task.name = data.get('name', task.name)
        task.func = data.get('functions', task.func)
        task.trigger = data.get('type', task.trigger)
        
        # 更新触发器参数
        trigger_args = {}
        if data.get('type') == 'date':
            if data.get('datetime'):
                task.start_date = datetime.datetime.strptime(data['datetime'], '%Y-%m-%d %H:%M:%S')
        elif data.get('type') == 'interval':
            if data.get('time'):
                try:
                    trigger_args = json.loads(data['time'])
                except json.JSONDecodeError:
                    time_parts = data['time'].split(':')
                    if len(time_parts) == 3:
                        hours = int(time_parts[0])
                        minutes = int(time_parts[1])
                        seconds = int(time_parts[2])
                        trigger_args = {
                            'hours': hours,
                            'minutes': minutes,
                            'seconds': seconds
                        }
        elif data.get('type') == 'cron':
            if data.get('time'):
                try:
                    trigger_args = json.loads(data['time'])
                except json.JSONDecodeError:
                    time_parts = data['time'].split(':')
                    if len(time_parts) == 2:
                        trigger_args = {
                            'hour': int(time_parts[0]),
                            'minute': int(time_parts[1])
                        }
        
        task.trigger_args = json.dumps(trigger_args)
        task.updated_at = datetime.datetime.now()
        
        # 保存到数据库
        db.session.commit()
        
        # 更新调度器中的任务
        from apps.extensions.scheduler import remove_job_from_task, add_job_from_task
        remove_job_from_task(task_id)
        job = add_job_from_task(task)
        
        if job:
            return jsonify({'success': True, 'msg': '任务更新成功'})
        else:
            return jsonify({'success': False, 'msg': '任务更新成功，但调度器更新失败'})
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'msg': f'更新任务失败: {str(e)}'})

@task_bp.route('/remove/<task_id>', methods=['DELETE'])
@authorize('admin:task:remove')
def remove(task_id):
    """删除任务"""
    try:
        task = Task.query.get(task_id)
        if not task:
            return jsonify({'success': False, 'msg': '任务不存在'})
        
        # 从调度器中移除
        from apps.extensions.scheduler import remove_job_from_task
        remove_job_from_task(task_id)
        
        # 从数据库中删除
        db.session.delete(task)
        db.session.commit()
        
        return jsonify({'success': True, 'msg': '任务删除成功'})
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'msg': f'删除任务失败: {str(e)}'})

@task_bp.route('/enable', methods=['PUT'])
@authorize('admin:task:edit')
def enable():
    """启用任务"""
    try:
        data = request.get_json()
        task_id = data.get('id')
        
        task = Task.query.get(task_id)
        if not task:
            return jsonify({'success': False, 'msg': '任务不存在'})
        
        # 启用任务
        task.enabled = True
        db.session.commit()
        
        # 添加到调度器
        from apps.extensions.scheduler import add_job_from_task
        job = add_job_from_task(task)
        
        if job:
            return jsonify({'success': True, 'msg': '任务启用成功'})
        else:
            return jsonify({'success': False, 'msg': '任务启用成功，但添加到调度器失败'})
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'msg': f'启用任务失败: {str(e)}'})

@task_bp.route('/disable', methods=['PUT'])
@authorize('admin:task:edit')
def disable():
    """禁用任务"""
    try:
        data = request.get_json()
        task_id = data.get('id')
        
        task = Task.query.get(task_id)
        if not task:
            return jsonify({'success': False, 'msg': '任务不存在'})
        
        # 禁用任务
        task.enabled = False
        db.session.commit()
        
        # 从调度器中移除
        from apps.extensions.scheduler import remove_job_from_task
        remove_job_from_task(task_id)
        
        return jsonify({'success': True, 'msg': '任务禁用成功'})
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'msg': f'禁用任务失败: {str(e)}'})

@task_bp.route('/run/<task_id>', methods=['POST'])
@authorize('admin:task:edit')
def run_now(task_id):
    """立即运行任务"""
    try:
        task = Task.query.get(task_id)
        if not task:
            return jsonify({'success': False, 'msg': '任务不存在'})
        
        # 获取任务函数
        task_func = get_task_function(task.func)
        if not task_func:
            return jsonify({'success': False, 'msg': '任务函数不存在'})
        
        # 立即执行任务
        result = task_func['func']()
        
        return jsonify({'success': True, 'msg': f'任务执行成功: {result}'})
        
    except Exception as e:
        return jsonify({'success': False, 'msg': f'任务执行失败: {str(e)}'})

@task_bp.route('/functions')
@authorize('admin:task:main')
def get_functions():
    """获取可用的任务函数列表"""
    try:
        functions = get_task_functions()
        function_list = []
        for func_name, func_info in functions.items():
            function_list.append({
                'name': func_name,
                'title': func_info['name'],
                'description': func_info['description']
            })
        
        return jsonify({
            'success': True,
            'data': function_list
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'msg': f'获取函数列表失败: {str(e)}'
        })